import React, { useState, useEffect, forwardRef, useImperativeHandle, useRef, use } from 'react';
import { Button, Table, Form, Select, message, Spin, Space } from 'antd';
import dayjs from 'dayjs';
import { reviewStatus, env } from '@/utils/data';
import Icon from '@/components/layout/Icon';
import { colWidth } from '@/utils/tools';
import CloseIcon from '@/components/close';
import MyModal from '@/components/modal';
import { deleteRelationApi, updateReviewApi, codeCheckApi, getProjectsApi, updateRelationApi } from '@/request/story';
import { searchApi, getBranchCommitApi } from '@/request/gitlab';
import { getListApi } from '@/request/personManage';
import { ColumnGroupType, ColumnType } from 'antd/es/table';
import styles from './index.module.css';
import SelectAdd from '../selecetAdd';

// record =>>>>>>>
// {
//   "project_id": 282,
//   "namespace": "easyhome-fe",
//   "project_name": "easyhome-workflow-manage",
//   "branch": "develop_code_20230425",
//   "review_status": 0 | 1 | 2,
//   "commit": {
//       "id": "c5d892b87a3a37c4e8ec6226a263b17e9c6c34fe",
//       "short_id": "c5d892b8",
//       "created_at": "2023-05-23T23:33:54.000+08:00",
//       "parent_ids": null,
//       "title": "feat：功能",
//       "message": "feat：功能",
//       "author_name": "赵美阳",
//       "author_email": "test@qq.com",
//       "authored_date": "2023-05-23T23:33:54.000+08:00",
//       "committer_name": "赵美阳",
//       "committer_email": "test@qq.com",
//       "committed_date": "2023-05-23T23:33:54.000+08:00",
//       "trailers": null,
//       "web_url": "http://gitlab.jrdaimao.com/easyhome-fe/easyhome-workflow-manage/-/commit/c5d892b87a3a37c4e8ec6226a263b17e9c6c34fe"
//   },
// }
// <<<<<<= record

const commitColumns: (ColumnGroupType<never> | ColumnType<never>)[] = [
  {
    title: '提交人',
    dataIndex: 'committer_name',
    width: 100,
    align: 'center',
  },
  {
    title: '提交日期',
    dataIndex: 'committed_date',
    width: 180,
    render(text) {
      return <span>{dayjs(text).format('YYYY-MM-DD')}</span>;
    },
  },
  {
    title: '提交Message',
    dataIndex: 'message',
  },
];

interface DiffData {
  namespace: string;
  from_project_id: number | string;
  source: string;
  target: string;
}

interface RelationProjectItem {
  project_id: number | string;
  namespace: string;
  project_name: string;
  branch: string;
  mainBranch?: string;
}

interface Project {
  id: number | string;
  namespace: {
    name: string;
  };
  name: string;
  branch: string;
  default_branch: string;
  http_url_to_repo: string;
}

const RelationTable = (props, ref) => {
  const { onOkCallback, myRecord, columns, style, scrollY = 337 } = props;
  const [projectDialog, setProjectDialog] = useState(false); // 选择项目弹框
  const [projects, setProjects] = useState<any>([]); // 项目列表
  const [developers, setDevelopers] = useState<any>([]); // 开发人员
  const [tableSource, setTableSource] = useState<any>([]); // 需求已经关联的项目
  const [relationTitile, setRelationTitle] = useState<string>(''); // 需求关联项目弹框title
  const [commitDialog, setCommitDialog] = useState<boolean>(false); // 提交记录弹框
  const [confirmDialog, setConfirmDialog] = useState<boolean>(false); // 二次确认弹框
  const [curProject, setCurProject] = useState<any>({});
  const [curProjectIndex, setCurProjectIndex] = useState('');
  const [commitDataSource, setCommitDataSource] = useState([]); // 提交记录
  const [projectForm] = Form.useForm();
  const tapd = useRef<any>(null); // 当前某个需求
  const [isEdit, setIsEdit] = useState(false); // 是否修改关联项目还是添加关联项目
  const [spinning, setSpinning] = useState(false); // 编辑 loading
  const [developEnv, setDevelopEnv] = useState<any>([]); // 开发环境下拉框
  const [checkLoading, setCheckLoading] = useState<boolean>(false); // 代码质量检查按钮loading
  const search = (input, option) => `${String(option.name)}`.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  const timeout = useRef<ReturnType<typeof setTimeout> | null>(null); // 定时器
  // 通过接口获取当前需求关联的项目
  const getStoryWithProject = async (id) => {
    const result: any = await getProjectsApi({ id });
    const res = result.filter((item) => item.type !== 2);
    setTableSource(res || []);
  };

  useEffect(() => {
    if (myRecord.id) {
      // 接收过来的数据
      tapd.current = myRecord;
      // 修改弹框标题
      setRelationTitle(myRecord.name);
      // 给表格初始数据
      // setTableSource(record.relation_projects || []);
      // 获取需求关联的项目
      getStoryWithProject(myRecord.id);
    }
  }, [myRecord]);
  // 获取所有项目
  // 传空查所有，有查询条件按照查询条件进行查询
  const getProjectsList = async (params = {}) => {
    try {
      const ret = await searchApi(params);
      if (ret) {
        setProjects(ret);
      }
    } catch (err: any) {
      console.log(err);
    }
  };
  // 获取开发人员
  const getDeveloper = async () => {
    try {
      const res = await getListApi({});
      if (res) {
        setDevelopers(res);
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };

  // 获取根据项目名称模糊查询列表
  // 文本框值变化时回调
  const fetchProject = (value: string) => {
    if (timeout.current) {
      clearTimeout(timeout.current);
      timeout.current = null;
    }
    if (value) {
      timeout.current = setTimeout(() => {
        getProjectsList({ name: value });
      }, 300);
    } else {
      getProjectsList();
    }
  };

  // 项目下拉框改变
  const handleProjectChange = (value) => {
    if (value) {
      // getBranchesList(value);
      projectForm.setFieldsValue({
        branch: undefined,
        env: undefined,
      });
      const data: any = projects.filter((item: any) => item.id === value)[0];
      if (data.envs) {
        const result = env.filter((item) => data.envs.includes(item.value));
        setDevelopEnv(result);
      }
      return data[0];
    }
    setDevelopEnv([]);
    return {};
  };

  // 查看提交记录
  const handleCommit = async (record) => {
    const res: any = await getBranchCommitApi({
      id: record.project_id,
      ref_name: record.branch,
      all: true,
      per_page: 100,
      page: 1,
    });
    if (res) {
      setCommitDialog(true);
      setCommitDataSource(res);
    }
  };
  // 编辑关联的项目
  const handleEditProject = async (record, index) => {
    try {
      setIsEdit(index);
      setProjectDialog(true);
      setSpinning(true);
      await getProjectsList();
      // await getBranchesList(record.project_id);
      setSpinning(false);
      projectForm.setFieldsValue({
        project: record.project_id,
        branch: record.branch,
        env: record.env,
      });
    } catch (err: any) {
      console.log(err.message);
      setSpinning(false);
    }
  };

  // 删除关联的项目
  const handleDeleteProject = async (record, index) => {
    try {
      const res = await deleteRelationApi({ index, info: { id: tapd.current.id, ...record } });
      if (res) {
        const copy = [...tableSource];
        message.success('删除成功');
        // 手动维护前端数据
        copy.splice(index, 1);
        setTableSource(copy);
        setConfirmDialog(false);
        setCurProject({});
        setCurProjectIndex('');
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };
  // 弹出删除确认弹框
  const handleShowConfirm = (record, index) => {
    setConfirmDialog(true);
    setCurProject(record);
    setCurProjectIndex(index);
  };
  // 更改项目的review状态
  const handleReviewStatus = async (record, index, e, type) => {
    const temp = {
      ...record,
      isEdit: index,
      id: tapd.current.id,
    };
    if (type === 'status') {
      temp.review_status = e;
    } else if (type === 'env') {
      if (e.length === 0) return;
      temp.env = e;
    }
    try {
      const res = await updateReviewApi(temp);
      if (res) {
        const copy = [...tableSource];
        message.success('保存成功');
        copy.splice(index, 1, temp);
        setTableSource(copy);
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };
  // diff分支
  const handleDiff = async (record: RelationProjectItem) => {
    const { branch, project_id } = record;
    const res: any = await searchApi({ id: project_id });
    const result: Project = res[0];
    const url = result.http_url_to_repo.split('.git')[0];
    if (!url) {
      message.error('错误的url');
      return;
    }
    const link = `${url}/-/compare/${result.default_branch}...${branch}?from_project_id=${result.id}`;
    window.open(link);
  };
  // 质量检查
  const handleCheckCode = async (record: RelationProjectItem) => {
    const { branch, project_id } = record;
    setCheckLoading(true);
    try {
      const res = await codeCheckApi({ branch, project_id });
      if (res) {
        message.success('请查看钉钉群通知');
      }
    } catch (err: any) {
      console.log(err.message);
    } finally {
      setCheckLoading(false);
    }
  };
  // 操作
  const handlerOperation = (type, record: RelationProjectItem, index, e) => {
    if (type === 'diff') {
      handleDiff(record);
    } else if (type === 'edit') {
      handleEditProject(record, index);
    } else if (type === 'record') {
      handleCommit(record);
    } else if (type === 'delete') {
      // handleDeleteProject(record, index);
      handleShowConfirm(record, index);
    } else if (type === 'status') {
      handleReviewStatus(record, index, e, 'status');
    } else if (type === 'check') {
      handleCheckCode(record);
    } else if (type === 'env') {
      handleReviewStatus(record, index, e, 'env');
    }
  };

  // 添加项目按钮
  const handleAddProject = () => {
    setIsEdit(false);
    setProjectDialog(true);
    getProjectsList();
    getDeveloper();
  };

  // 确认添加项目
  const onOkAddProject = async () => {
    const flag = await projectForm.validateFields();
    if (flag) {
      const data = projectForm.getFieldsValue();
      const curPro: any = projects.filter((item: any) => item.id === data.project)[0];
      const temp = {
        id: tapd.current.id, // 需求id
        project_id: curPro.id, // 项目id
        project_name: curPro.name, // 项目名称
        branch: data.branch, // 分支名称
        isEdit, // 编辑还是添加
        review_status: 0, // 是否review。默认为未查验
        env: data.env, // 开发环境
        developer: data.developer, // 开发人员
        http_url_to_repo: curPro.http_url_to_repo, // 项目git地址
      };
      try {
        // 往需求的数据里新增或编辑
        const res = await updateRelationApi(temp);
        if (res) {
          const copy = [...tableSource];
          message.success('保存成功');
          if (typeof isEdit === 'number') {
            copy.splice(isEdit, 1, temp);
          } else {
            copy.push(temp);
          }
          setTableSource(copy);
          setProjectDialog(false);
          projectForm.resetFields();
          // 判断环境使用记录。维护脑图。
          // judgeEnvUsed(res, temp);
          onOkCallback?.();
        }
      } catch (err: any) {
        console.log(err.message);
      }
    }
  };

  useImperativeHandle(ref, () => ({
    handleOpen() {
      setIsEdit(false);
      setProjectDialog(true);
      getProjectsList();
      getDeveloper();
    },
  }));

  const myColumns = columns?.(handlerOperation, checkLoading, developEnv) || [];

  return (
    <div className="relation-dialog" style={style}>
      <Table
        pagination={false}
        scroll={{ x: colWidth(myColumns), y: scrollY }}
        columns={myColumns}
        dataSource={tableSource}
        rowKey={(record: { project_id: string | number; branch: string; env: string }) => `${record.project_id}_${record.branch}_${record.env}`}
      ></Table>
      {/* 选择项目 */}
      <MyModal
        style={{ top: '184px' }}
        width={600}
        destroyOnClose
        title="添加关联项目"
        open={projectDialog}
        closeIcon={<CloseIcon />}
        onCancel={() => {
          setProjectDialog(false);
          projectForm.resetFields();
          setDevelopEnv([]);
        }}
        onOk={() => {
          onOkAddProject();
        }}
      >
        <div style={{ position: 'relative' }}>
          <div style={{ textAlign: 'center' }}>
            <Spin spinning={spinning} />
          </div>
          <Form form={projectForm} colon={false}>
            <Form.Item label="选择项目" name="project" rules={[{ required: true, message: '请选择项目' }]}>
              <Select placeholder="请选择项目" options={projects} onSearch={fetchProject} onChange={handleProjectChange} filterOption={false} showSearch fieldNames={{ label: 'name', value: 'id' }} />
            </Form.Item>
            <Form.Item label="开发分支" name="branch" rules={[{ required: true, message: '请选择分支' }]}>
              <SelectAdd projects={projects} projectId={projectForm.getFieldValue('project')} />
              {/* <Select placeholder="请选择开发分支" options={branches} filterOption={search} showSearch fieldNames={{ label: 'name', value: 'name' }} /> */}
            </Form.Item>
            <Form.Item label="开发环境" name="env" rules={[{ required: true, message: '请选择环境' }]}>
              <Select placeholder="请选择开发环境" options={developEnv} mode="multiple" />
            </Form.Item>
            <Form.Item label="开发人员" name="developer" rules={[{ required: true, message: '请选择人员' }]} style={{ marginBottom: '0' }}>
              <Select mode="multiple" placeholder="请选择" options={developers} filterOption={search} showSearch fieldNames={{ label: 'name', value: 'name' }} />
            </Form.Item>
          </Form>
        </div>
      </MyModal>
      {/* 提交记录弹框 */}
      <MyModal
        destroyOnClose
        title="提交记录"
        open={commitDialog}
        width={1000}
        onCancel={() => {
          setCommitDialog(false);
        }}
      >
        <Table dataSource={commitDataSource} columns={commitColumns} rowKey="id" scroll={{ y: scrollY - 20 }}></Table>
      </MyModal>
      {/* 二次确认弹框 */}
      <MyModal
        destroyOnClose
        title="提示"
        open={confirmDialog}
        width={600}
        onCancel={() => {
          setConfirmDialog(false);
          setCurProject({});
          setCurProjectIndex('');
        }}
        onOk={() => {
          handleDeleteProject(curProject, curProjectIndex);
        }}
      >
        <div>{`确认取消与"${relationTitile}的关联吗？`}</div>
      </MyModal>
    </div>
  );
};

export default forwardRef(RelationTable);
